<script lang="ts" setup>
import { ref, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElTree, ElLoading } from 'element-plus'
import wsjzglService from '@/api/wsjzgl'
import AddDialog from './dialogs/add-dialog.vue'
import MlmbDialog from './dialogs/mlmb-dialog.vue'
import AddmlDialog from './dialogs/add-ml-dialog.vue'
import UpdatemlDialog from './dialogs/update-ml-dialog.vue'
import zzmlDialog from './dialogs/zzml-dialog.vue'
import TreeUtilDTO from '@/utils/tree'
import { useMainStore } from '@/store/main'
import { mlxxMainStore } from '@/store/mlxx'
import { useRoute } from 'vue-router'
const route = useRoute()
const mlxxStore = mlxxMainStore()
const emit = defineEmits(['nodeClick'])
const store = useMainStore()
defineProps({
  ajxxIsShowZzml: {
    type: Object,
    default: null,
  },
})
// 入参

// 生命周期
// onMounted(() => {
//   // 查询树
//   queryTree()
// })

const init = () => {
  queryTree()
  treeNodeData.value = {}
}

const filterForm = ref({
  gjzValue: '',
  mlSelect: '0',
})
const options = [
  {
    value: '0',
    label: '所有目录',
  },
  {
    value: '1',
    label: '纸质目录',
  },
]

const defaultProps = {
  children: 'children',
  label: 'mc',
}
const treeData = ref<any>([])
const dbmNode = ref<any>()
const firtsNode = ref<any>()

const getFirstNode = (arr: any[]) => {
  if (firtsNode.value) return
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].children && arr[i].children.length > 0) {
      getFirstNode(arr[i].children)
    } else {
      firtsNode.value = arr[i]
    }
    return
  }
}

const handleCheckNode = (node: any) => {
  nextTick(() => {
    treeNodeClick(node)
    treeRef.value!.setCurrentKey(node.bh)
  })
}
/*
 * 查询树
 */
const addTjjList = ref()
const queryTree = () => {
  const params = {
    ajbh: route.query.ajbh as unknown as string,
    mlmc: '',
    mlxslx: mlxslx.value,
    smrbh: store.userInfo?.ryid,
    smrxm: store.userInfo?.xm,
  }
  wsjzglService
    .queryAjmls(params)
    .then((res) => {
      const obj = route.query
      addTjjList.value = res.data
      dbmNode.value = res.data?.find((item: any) => item.mc === '待编目材料')
      store.saveJzsmDbmNode(dbmNode.value)
      const zjNode = res.data?.find((item: any) => item.mc === '正卷')
      const fjNode = res.data?.find((item: any) => item.mc === '副卷')
      store.saveZjNode(zjNode)
      store.saveFjNode(fjNode)
      // res.data?.forEach((item: any) => {
      //   if (item.bh !== dbmNode.value.bh && item.ajbh !== dbmNode.value.bh) {
      //     item['disabled'] = true
      //   }
      //   if (!item.fbh) {
      //     item['fbh'] = obj.ajbh
      //   }
      // })
      res.data = res.data?.filter((item: any) => {
        if (
          item.bh !== dbmNode.value.bh &&
          item.ajbh !== dbmNode.value.bh &&
          item.fbh !== dbmNode.value.bh
        ) {
          return false
        }
        if (!item.fbh) {
          item['fbh'] = obj.ajbh
        }
        return true
      })
      //处理数据
      res.data.push({
        ajbhaj: obj.ajbh,
        bh: obj.ajbh,
        mc: obj.ajmc,
        wjsl: 0,
      })
      treeData.value = TreeUtilDTO.getTreeData(res.data, 'bh', 'fbh')
      treeData.value?.forEach((data: any) => {
        if (data.children && data.children.length > 0) {
          data.children.forEach((data1: any) => {
            data.wjsl += data1.wjsl
            if (data1.children) {
              data1.children = data1.children.sort((a: any, b: any) => a.mlsxh - b.mlsxh)
            }
          })
        }
      })

      if (treeData.value.length) {
        firtsNode.value = null
        // 递归选择第一个
        getFirstNode(treeData.value)
        if (firtsNode.value) {
          handleCheckNode(firtsNode.value)
        }
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

/*
 * 树节点点击（抛出方法到主界面）
 */
const treeNodeData = ref()
const treeNodeClick = (data: any) => {
  if (treeNodeData.value?.bh === data.bh) {
    store.saveNodeTreeData(data)
    return
  }
  treeNodeData.value = data
  emit('nodeClick', treeNodeData.value)
  mlClose()
}

// 抛出去刷新再请求一次方法
const againTreeData = () => {
  const params = {
    ajbh: route.query.ajbh as unknown as string,
    mlmc: '',
    mlxslx: mlxslx.value,
    smrbh: store.userInfo?.ryid,
    smrxm: store.userInfo?.xm,
  }
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  wsjzglService
    .queryAjmls(params)
    .then((res) => {
      const obj = route.query
      dbmNode.value = res.data?.find((item: any) => item.mc === '待编目材料')
      store.saveJzsmDbmNode(dbmNode.value)
      const zjNode = res.data?.find((item: any) => item.mc === '正卷')
      const fjNode = res.data?.find((item: any) => item.mc === '副卷')
      store.saveZjNode(zjNode)
      store.saveFjNode(fjNode)
      // res.data?.forEach((item: any) => {
      //   if (item.bh !== dbmNode.value.bh && item.ajbh !== dbmNode.value.bh) {
      //     item['disabled'] = true
      //   }
      //   if (!item.fbh) {
      //     item['fbh'] = obj.ajbh
      //   }
      // })
      res.data = res.data?.filter((item: any) => {
        if (
          item.bh !== dbmNode.value.bh &&
          item.ajbh !== dbmNode.value.bh &&
          item.fbh !== dbmNode.value.bh
        ) {
          return false
        }
        if (!item.fbh) {
          item['fbh'] = obj.ajbh
        }
        return true
      })
      //处理数据
      res.data.push({
        ajbhaj: obj.ajbh,
        bh: obj.ajbh,
        mc: obj.ajmc,
        wjsl: 0,
      })
      treeData.value = TreeUtilDTO.getTreeData(res.data, 'bh', 'fbh')

      treeData.value?.forEach((data: any) => {
        if (data.children && data.children.length > 0) {
          data.children.forEach((data1: any) => {
            data.wjsl += data1.wjsl
            if (data1.children) {
              data1.children = data1.children.sort((a: any, b: any) => a.mlsxh - b.mlsxh)
            }
          })
        }
      })
      nextTick(() => {
        treeRef.value!.setCurrentKey(store.$state?.nodeTreeData?.bh)
        filterTree()
        emit('nodeClick', store.$state?.nodeTreeData, false)
      })
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.close()
    })
}

/*
 * 拖拽节点
 */

const handleDrop = (draggingNode: any, dropNode: any) => {
  let params
  if (dropNode.data.cj === '1') {
    params = {
      list: dropNode.data.children.map((el: any, i: number) => ({
        ajbh: dropNode.data.bh,
        mlbh: el.bh,
        mlsxh: i + 1,
      })),
    }
  } else if (dropNode.data.cj === '2') {
    const temp = TreeUtilDTO.findNode(treeData.value, dropNode.data.fbh, 'bh')
    params = {
      list: temp.children.map((el: any, i: number) => ({
        ajbh: temp.bh,
        mlbh: el.bh,
        mlsxh: i + 1,
      })),
    }
  }
  wsjzglService
    .updateMlgs(params, route.query.ajbh as string)
    .then(() => {
      againTreeData()
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

// 判断节点是否能被拖动
const allowDrag = (node: any) => {
  let flag = true
  if (node.data.disabled) {
    return false
  }
  if (node.data.cj === '2') {
    flag = true
  } else {
    flag = false
  }
  return flag && mlxxStore.isUnlockReadOnly
}

//目标节点能否成为拖动目标位置
const allowDrop = (draggingNode: any, dropNode: any, type: any) => {
  if (draggingNode.data.cj === dropNode.data.cj) {
    return type === 'prev' || type === 'next'
  } else if (draggingNode.data.cj === '2' && dropNode.data.cj === '1') {
    return type === 'inner'
  } else {
    return false
  }
}

/* 获取ref */
const addDialog = ref()
const mlmbDialog = ref()
const addmlDialog = ref()
const updatemlDialog = ref()

/*
 * 打开添加卷弹框
 */
const openAddJDialog = () => {
  //
  addDialog.value.openDialog(addTjjList.value)
}

/*
 * 删除卷
 */
const deleteJ = (e: any) => {
  ElMessageBox.confirm('此操作将永久删除该数据，是否继续?', '提示', {
    cancelButtonText: '取消',
    confirmButtonText: '确定',
    type: 'warning',
  }).then(() => {
    const params = {
      ajbh: e.ajbh,
      dabh: e.dabh,
    }
    wsjzglService
      .deleteAjxx(params, route.query.ajbh as string)
      .then((res) => {
        if (res.data.scjg) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          queryTree()
        }
      })
      .catch((err) => {
        !err.isError && ElMessage({ type: 'warning', message: err.message })
      })
  })
}

/*
 * 打开添加目录弹框
 */
const openAddMlDialog = (e: any) => {
  addmlDialog.value.openDialog(e)
}

/*
 * 删除案件目录
 */
const deleteAjml = (e: any) => {
  ElMessageBox.confirm('此操作将永久删除该数据，是否继续?', '提示', {
    cancelButtonText: '取消',
    confirmButtonText: '确定',
    type: 'warning',
  }).then(() => {
    const params = {
      ajbh: e.ajbh,
      mlbh: e.bh,
    }
    wsjzglService
      .deleteAjml(params, route.query.ajbh as string)
      .then((res) => {
        if (res.message === '成功') {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          queryTree()
        }
      })
      .catch((err) => {
        !err.isError && ElMessage({ type: 'warning', message: err.message })
      })
  })
}

/*
 * 导出目录
 */
const exportMl = (node: any) => {
  const params = {
    ajbh: node.ajbh,
  }
  wsjzglService
    .exportAjml(params)
    .then((res: any) => {
      const blob = new Blob([res])
      const objectUrl = URL.createObjectURL(blob)
      const link = document.createElement('a') // 创建a标签
      link.href = objectUrl
      link.download = `导出目录.xlsx` // 自定义文件名
      link.click() // 下载文件
      URL.revokeObjectURL(objectUrl) // 释放内存
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

/*
 * 导入目录
 */
const importMl = (e: any) => {
  updatemlDialog.value.openDialog(e)
}

/*
 * 打开目录模板弹框
 */
const openMlmbDialog = () => {
  mlmbDialog.value.openDialog(treeNodeData.value)
}

/*
 * 打开纸质目录弹框
 */
const zzmlDialogRef = ref()
const openZzmlDialog = () => {
  zzmlDialogRef.value.openDialog()
}

/* 树选择 */
const menuShow = ref(false)
const rightMenu = ref({
  top: '',
  left: '',
})

/* 获取节点信息 */
const nodeData = ref<any>({})
/* 树右键点击 */
const rightClick = (e: any, data: any) => {
  if (data.disabled || !data.fbh) return
  nodeData.value = data //节点信息保存,用于删除卷
  if (!nodeData.value?.wjbhList) {
    nodeData.value.wjbhList = []
  }
  for (let i = 0; i < treeData.value.length; i++) {
    if (treeData.value[i].bh === data.bh) {
      for (let j = 0; j < treeData.value[i]?.children?.length; j++) {
        nodeData.value.wjbhList.push(treeData.value[i].children[j].bh)
      }
      break
    }
  }

  //打开按钮目录
  menuShow.value = false // 先把模态框关死，目的是 第二次或者第n次右键鼠标的时候 它默认的是true
  menuShow.value = true
  e.preventDefault() //关闭浏览器右键默认事件
  rightMenu.value = { top: e.pageY + 'px', left: e.pageX + 'px' }
  document.addEventListener('click', (ev) => {
    // ev.stopImmediatePropagation()
    if (ev.target !== document.querySelector('.el-menu-item.is-active')) {
      mlClose()
    }
  })
  if (data.cj === '1') {
    if (data.mc === '待编目材料') {
      menuList.value = [{ text: '删除目录', disabled: true }]
    }
  } else {
    const fNode = TreeUtilDTO.findNode(treeData.value, data.fbh, 'bh')
    if (fNode.mc === '待编目材料') {
      if (store.zjNode && store.fjNode) {
        menuList.value = [
          { text: '删除目录', disabled: false || !mlxxStore.isUnlockReadOnly },
          {
            text: '移动到',
            disabled: false || !mlxxStore.isUnlockReadOnly,
            children: [{ text: '正卷' }, { text: '副卷' }],
          },
        ]
      } else if (store.zjNode && !store.fjNode) {
        menuList.value = [
          { text: '删除目录', disabled: false || !mlxxStore.isUnlockReadOnly },
          {
            text: '移动到',
            disabled: false || !mlxxStore.isUnlockReadOnly,
            children: [{ text: '正卷' }],
          },
        ]
      } else if (!store.zjNode && store.fjNode) {
        menuList.value = [
          { text: '删除目录', disabled: false || !mlxxStore.isUnlockReadOnly },
          {
            text: '移动到',
            disabled: false || !mlxxStore.isUnlockReadOnly,
            children: [{ text: '副卷' }],
          },
        ]
      } else if (!store.zjNode && !store.fjNode) {
        menuList.value = [{ text: '删除目录', disabled: false || !mlxxStore.isUnlockReadOnly }]
      }
      if (e.pageY + 82 > window.innerHeight) {
        rightMenu.value = { top: e.pageY - 82 + 'px', left: e.pageX + 'px' }
      }
    }
  }
}
/* 关闭目录 */
const mlClose = () => {
  // 取消鼠标监听事件 菜单栏
  menuShow.value = false
  document.removeEventListener('click', mlClose) // 关掉监听，
}
/* 目录列表 */
const menuList = ref([
  { text: '删除目录', disabled: false || !mlxxStore.isUnlockReadOnly },
  {
    text: '移动到',
    disabled: false || !mlxxStore.isUnlockReadOnly,
    children: [{ text: '正卷' }, { text: '副卷' }],
  },
])

// 右键菜单移动到
const moveVisible = ref(false)
const moveTo = (mc: string) => {
  const temp = TreeUtilDTO.findNode(treeData.value, mc, 'mc')
  const list = (temp.children || []).map((el: any, i: number) => ({
    ajbh: temp.bh,
    mlbh: el.bh,
    mlsxh: i + 1,
  }))
  list.push({
    ajbh: temp.bh,
    mlbh: nodeData.value.bh,
    mlsxh: (temp.children?.length || 0) + 1,
  })
  const params = {
    list,
  }
  wsjzglService
    .updateMlgs(params, route.query.ajbh as string)
    .then(() => {
      queryTree()
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}
/* 目录列表点击 */
const menuButton = (e: any) => {
  if (e.text === '删除卷') {
    deleteJ(nodeData.value)
  } else if (e.text === '添加目录') {
    openAddMlDialog(nodeData.value)
  } else if (e.text === '删除目录') {
    deleteAjml(nodeData.value)
  } else if (e.text === '导出目录') {
    exportMl(nodeData.value)
  } else if (e.text === '导入目录') {
    importMl(nodeData.value)
  } else if (e.text === '副卷') {
    moveVisible.value = false
    moveTo('副卷')
  } else if (e.text === '正卷') {
    moveVisible.value = false
    moveTo('正卷')
  }
}

const treeRef = ref<InstanceType<typeof ElTree>>()

// 文字过滤
const filterTree = () => {
  treeRef.value?.filter(filterForm.value.gjzValue)
}

const mlxslx = ref('0')
// 下拉过滤
const mlSelectChange = (val: string) => {
  mlxslx.value = val
  queryTree()
}

/**
 * 树节点过滤
 */
const filterNode = (value: any, data: any) => {
  let flag = true
  if (value) {
    if (typeof value === 'string') {
      // 文字过滤
      flag = data[defaultProps.label].indexOf(value) !== -1
    }
  }
  return flag
}

defineExpose({ init, againTreeData })
</script>
<template>
  <div class="container">
    <div class="top">
      <div class="top-conten">
        <div class="left">
          <button class="btn_operation" @click="openAddJDialog" :disabled="true">
            <div class="btn-add"></div>
            添加卷
          </button>
          <button class="btn_operation" @click="openMlmbDialog" :disabled="true">
            <div class="btn-wztz"></div>
            目录模板
          </button>
        </div>

        <button class="btn_operation" @click="openZzmlDialog" :disabled="true">
          <div class="btn-zzml"></div>
          纸质目录
        </button>
      </div>

      <div class="center">
        <el-input
          v-model="filterForm.gjzValue"
          autosize=""
          placeholder="请输入查询关键字"
          @change="filterTree"
        >
          <template #suffix>
            <el-icon @click="filterTree" class="el-input__icon"><Search /></el-icon>
          </template>
        </el-input>
        <el-select v-model="filterForm.mlSelect" placeholder="请选择" @change="mlSelectChange">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
    </div>
    <div class="bottom">
      <el-tree
        ref="treeRef"
        style="max-width: 600px"
        :data="treeData"
        draggable
        node-key="bh"
        highlight-current
        :expand-on-click-node="false"
        :props="defaultProps"
        @node-contextmenu="rightClick"
        @node-click="treeNodeClick"
        :filter-node-method="filterNode"
        @node-drop="handleDrop"
        :allow-drag="allowDrag"
        :allow-drop="allowDrop"
      >
        <template #default="{ data }">
          <div class="custom-tree-node" :class="{ 'node-is-disabled': data.disabled }">
            <img v-if="!data.fbh" src="/src/assets/images/file-icon.png" alt="" />
            <img
              v-if="data.mc === '正卷' || data.mc === '副卷'"
              src="/src/assets/images/dbm.png"
              alt=""
            />
            <img v-if="data.mc === '待编目材料'" src="/src/assets/images/juan.png" alt="" />
            <img
              v-if="data.cj === '2' && data.sfdzajml === 'Y' && (data.sfyy === 'N' || !data.sfyy)"
              style="margin-right: 5px"
              src="/src/assets/images/xswjwyz.png"
              alt=""
            />
            <img
              v-if="data.cj === '2' && data.sfdzajml === 'Y' && data.sfyy === 'Y'"
              style="margin-right: 5px"
              src="/src/assets/images/xsxwjyyz.png"
              alt=""
            />
            <img
              v-if="data.cj === '2' && (data.sfzzajml === 'Y' || !data.sfzzajml)"
              src="/src/assets/images/xxwj.png"
              alt=""
            />
            <span :class="data.cj === '2' ? 'over-title' : ''" :title="data.mc"
              >&nbsp;{{ data.mc }}&nbsp;</span
            >
            <span>({{ data.wjsl }})</span>
          </div>
        </template>
      </el-tree>
      <!-- 树形控件右键组件 -->
      <div v-show="menuShow" class="tree-right-menu" :style="{ ...rightMenu }">
        <template v-for="(item, index) in menuList" :key="index">
          <el-button
            v-if="item.text !== '移动到'"
            class="right-btn"
            type="primary"
            text
            :disabled="item.disabled"
            @click="menuButton(item)"
          >
            {{ item.text }}
          </el-button>
          <el-popover
            v-else
            placement="right-start"
            popper-class="move-to"
            :show-arrow="false"
            :visible="moveVisible"
            :hide-after="0"
          >
            <template #reference>
              <div class="right-btn" @mouseenter="moveVisible = true">
                {{ item.text }}
              </div>
            </template>
            <div @mouseleave="moveVisible = false">
              <div
                class="right-btn"
                v-for="(el, i) in item.children"
                :key="i"
                @click="menuButton(el)"
              >
                {{ el.text }}
              </div>
            </div>
          </el-popover>
        </template>
      </div>
    </div>
    <AddDialog ref="addDialog" @refresh="queryTree" />
    <MlmbDialog ref="mlmbDialog" @refresh="queryTree" />
    <AddmlDialog ref="addmlDialog" @refresh="queryTree" />
    <UpdatemlDialog ref="updatemlDialog" @refresh="queryTree" />
    <!-- 纸质目录 -->
    <zzmlDialog ref="zzmlDialogRef"></zzmlDialog>
  </div>
</template>
<style lang="scss">
.move-to {
  padding: 0 !important;
  width: 98px !important;
  min-width: 98px !important;
}
</style>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  .top {
    .top-conten {
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
      .left {
        display: flex;
      }
      .btn_operation {
        white-space: nowrap;
      }
      .btn_operation {
        padding: 0 8px;
      }
      .btn_operation + .btn_operation {
        margin-left: 6px;
      }
    }

    height: 82px;
    .center {
      display: flex;
      padding-bottom: 10px;
      border-bottom: 1px solid rgba(0, 0, 0, 0.15);
      .el-input {
        flex: 1;
      }
      .el-select {
        width: 102px;
        margin-left: 10px;
      }
    }
  }

  .bottom {
    height: calc(100% - 82px);
    overflow-y: auto;
    .tree-right-menu {
      padding: 8px 0;
      position: fixed;
      width: 100px;
      box-shadow: 0px 1px 5px 0px rgba(0, 0, 0, 0.15);
      border-radius: 5px;
      border: solid 1px #dce5f5;
      z-index: 1000;
      background-color: #fff;
      display: flex;
      flex-direction: column;
      align-items: center;
    }
  }
}
.el-input__icon {
  cursor: pointer;
}
.right-btn {
  margin: 0;
  color: #4b5881;
  width: 100%;
  padding: 8px 15px;
  text-align: center;
  cursor: pointer;
  line-height: 16px;
  & > span {
    display: inline-block;
  }
  &.is-disabled {
    color: #b8bdc3 !important;
  }
  &:hover {
    background-color: #f5f5f5 !important;
  }
}
.custom-tree-node {
  width: calc(100% - 40px);
  display: flex;
  align-items: center;
  .over-title {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  &.node-is-disabled {
    color: #9f9f9f;
    cursor: not-allowed;
    pointer-events: none;
    height: 100%;
  }
}

:deep(.el-tabs .el-tabs__content) {
  height: calc(100% - 40px);
  /* overflow: auto; */
  padding: 0;
}

:deep(.el-tree) {
  color: #000;
}
</style>
